<template>
  <div class="basicConfig_container">
    <!-- LAN设置 -->
  <!--   <el-card>
      <template #header>
        <div class="flex items-center">
          <el-icon class="m-r-10px"><Connection /></el-icon>
          <span>{{t('networkConfig.lan_setting_label')}}</span>
        </div>
      </template>
      <el-form ref="lanForm" :model="lanFormData" :rules="lanFormRules" :hide-required-asterisk="true">
        <el-form-item :label="t('networkConfig.local_ip_label')" prop="localIp">
          <div class="flex">
            <el-input ref="localIpInput" v-model="lanFormData.localIp" :placeholder="t('networkConfig.ip_address_label')" />
            <el-button class="m-l-10px" type="primary" :loading="lanFormData.loading" @click="saveLocalIp">{{t('networkConfig.save_label')}}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card> -->

    <!-- CAA/GRE配置 -->
   <!--  <el-card class="m-t-20">
      <template #header>
        <div class="flex items-center">
          <el-icon class="m-r-10px"><SetUp /></el-icon>
          <span>{{t('networkConfig.caa_or_gre_label')}}</span>
        </div>
      </template>
      <el-table :data="caaOrGreDataList">
        <el-table-column :label="t('networkConfig.business_network_port_label')" prop="caa_ip" />
        <el-table-column :label="t('networkConfig.caaStart_label')" prop="caa_status">
          <template v-slot="{row}">
            <TagRender :value="row.caa_status" name="basicSettingsSwitch" />
          </template>
        </el-table-column>
        <el-table-column :label="t('networkConfig.greStart_label')" prop="gre_status">
          <template v-slot="{row}">
            <TagRender :value="row.gre_status" name="basicSettingsSwitch" />
          </template>
        </el-table-column>
        <el-table-column :label="t('networkConfig.edit_label')">
          <template v-slot="{row}">
            <el-button type="primary" @click="editCaaOrGre(row)">{{t('networkConfig.edit_label')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card> -->

    <!-- 反向NAT -->
    <el-card class="m-t-20">
      <template #header>
        <div class="flex items-center">
          <el-icon class="m-r-10px"><Share /></el-icon>
          <span>{{t('networkConfig.reverse_nat_label')}}</span>
        </div>
      </template>
      <el-table :data="reverseNatList">
        <el-table-column :label="t('networkConfig.built_in_host_ip_label')" prop="ip" />
        <el-table-column :label="t('networkConfig.enable_status_label')" prop="status">
          <template v-slot="{row}">
            <TagRender :value="row.status" name="basicSettingsSwitch" />
          </template>
        </el-table-column>
        <el-table-column :label="t('networkConfig.edit_label')">
          <template v-slot="{row}">
            <div class="global_btn" @click="editReverseNat(row)">
              <el-icon class="m-r-10px"><Edit /></el-icon>
             {{t('networkConfig.edit_label')}}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- WIFI设置 -->
    <el-card class="m-t-20">
      <template #header>
        <div class="flex items-center">
          <el-icon class="m-r-10px"><Monitor /></el-icon>
          <span>{{t('networkConfig.wifi_setting_label')}}</span>
        </div>
      </template>
      <el-table :data="wifiSettingList">
        <el-table-column :label="t('networkConfig.band_type_label')" prop="frequency_band" />
        <el-table-column :label="t('networkConfig.ssid_label')" prop="ssid" />
        <el-table-column :label="t('networkConfig.password_label')" prop="password" />
        <el-table-column :label="t('networkConfig.enable_status_label')" prop="status">
          <template v-slot="{row}">
            <TagRender :value="row.status" name="basicSettingsSwitch" />
          </template>
        </el-table-column>
        <el-table-column :label="t('networkConfig.edit_label')">
          <template v-slot="{row}">
            <div class="global_btn" @click="editWifiSetting(row)">
              <el-icon class="m-r-10px"><Edit /></el-icon>
              {{t('networkConfig.edit_label')}}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- DHCP设置 -->
    <el-card class="m-t-20">
      <template #header>
        <div class="flex items-center">
          <el-icon class="m-r-10px"><Setting /></el-icon>
          <span>{{t('networkConfig.dhcp_setting_label')}}</span>
        </div>
      </template>
      <el-table :data="dhcpSettingList">
        <el-table-column :label="t('networkConfig.start_ip_label')" prop="start_ip" />
        <el-table-column :label="t('networkConfig.end_ip_label')" prop="end_ip" />
        <el-table-column :label="t('networkConfig.DNS1_label')" prop="DNS1" />
        <el-table-column :label="t('networkConfig.DNS2_label')" prop="DNS2" />
        <el-table-column :label="t('networkConfig.enable_status_label')" prop="status">
          <template v-slot="{row}">
            <TagRender :value="row.status" name="basicSettingsSwitch" />
          </template>
        </el-table-column>
        <el-table-column :label="t('networkConfig.edit_label')">
          <template v-slot="{row}">
            <div class="global_btn" @click="editDhcpSetting(row)">
              <el-icon class="m-r-10px"><Edit /></el-icon>
              {{t('networkConfig.edit_label')}}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- IP加速 -->
    <el-card class="m-t-20">
      <template #header>
        <div class="flex items-center">
          <el-icon class="m-r-10px"><Cpu /></el-icon>
          <span>{{t('networkConfig.ip_acceleration_label')}}</span>
        </div>
      </template>
      <div class="flex items-center">
        <span class="m-r-10px text-16px">{{switchStates.ipAcceleration.status === 'on' ? t('networkConfig.enable_label') : t('networkConfig.disable_label')}}</span>
        <el-switch v-model="switchStates.ipAcceleration.status" :loading="switchStates.ipAcceleration.loading" @change="(value:any)=>handleSwitchChange('ipAcceleration',value)" active-value="on" inactive-value="off" />
      </div>
    </el-card> 

    <!-- ALOHA -->
  <!--   <el-card class="m-t-20">
      <template #header>
        <div class="flex items-center">
          <el-icon class="m-r-10px"><Operation /></el-icon>
          <span>{{t('networkConfig.aloha_label')}}</span>
        </div>
      </template>
      <div class="flex items-center">
        <span class="m-r-10px text-16px">{{switchStates.aloha.status === 'on' ? t('networkConfig.enable_label') : t('networkConfig.disable_label')}}</span>
        <el-switch v-model="switchStates.aloha.status" :loading="switchStates.aloha.loading" @change="(value:any)=>handleSwitchChange('aloha',value)" active-value="on" inactive-value="off" />
      </div>
    </el-card>

    <!-- Dialog保持不变 -->
    <Dialog v-bind="dialogConfig" v-model:dialogVisible="dialogConfig.dialogVisible">
      <template #content>
        <div class="caaOrGre_content p-20px" >
          <div v-if="dialogConfig.dialogType === 'caaOrGre'">
           <el-form ref="caaOrGreFormRef"  :model="caaOrGreFormData" label-width="auto" :rules="caaOrGreFormRules" label-position="left" >
            <el-form-item :label="t('networkConfig.greStart_label')" prop="caa_status">
               <el-switch v-model="caaOrGreFormData.caa_status" active-value="on" inactive-value="off" />
            </el-form-item>
            <el-form-item :label="t('networkConfig.greStart_label')" prop="gre_status">
              <el-switch v-model="caaOrGreFormData.gre_status" active-value="on" inactive-value="off" />
            </el-form-item>
            <el-form-item :label="t('networkConfig.business_network_port_label')" prop="caa_ip">
              <el-input   v-model="caaOrGreFormData.caa_ip" :placeholder="t('networkConfig.business_network_port_label')" />
            </el-form-item>
           </el-form>
         
          </div>
          <div v-else-if="dialogConfig.dialogType === 'reverseNat'">
            <el-form ref="reverseNatFormRef"  :model="reverseNatFormData"  label-width="auto" :rules="reverseNatFormRules" label-position="left" >
              <el-form-item :label="t('networkConfig.reverse_nat_label')" prop="ip">
                <el-input v-model="reverseNatFormData.ip" :placeholder="t('networkConfig.reverse_nat_label')" />
              </el-form-item>
              <el-form-item :label="t('networkConfig.enable_status_label')" prop="status"> 
                <el-switch v-model="reverseNatFormData.status" active-value="on" inactive-value="off" />
              </el-form-item>
            </el-form>
          </div>
          <div v-else-if="dialogConfig.dialogType === 'wifiSetting'">
            <el-form ref="wifiSettingFormRef"  label-width="auto" :model="wifiSettingFormData" :rules="wifiSettingFormRules" label-position="left" > 
              <el-form-item :label="t('networkConfig.band_type_label')" prop="frequency_band">
                 <el-input v-model="wifiSettingFormData.frequency_band" disabled :placeholder="t('networkConfig.band_type_label')" />
              </el-form-item>
              <el-form-item :label="t('networkConfig.ssid_label')" prop="ssid">
                <el-input v-model="wifiSettingFormData.ssid" :placeholder="t('networkConfig.ssid_label')" />
              </el-form-item>
              <el-form-item :label="t('networkConfig.password_label')" prop="password">
                <el-input v-model="wifiSettingFormData.password" :placeholder="t('networkConfig.password_label')" />
              </el-form-item>
              <el-form-item :label="t('networkConfig.enable_status_label')" prop="status"> 
                <el-switch v-model="wifiSettingFormData.status" active-value="on" inactive-value="off" />
              </el-form-item>
            </el-form>
          </div>
          <div v-else-if="dialogConfig.dialogType === 'dhcpSetting'">
            <el-form ref="dhcpSettingFormRef"  label-width="auto" :model="dhcpSettingFormData" :rules="dhcpSettingFormRules" label-position="left" > 
              <el-form-item :label="t('networkConfig.enable_status_label')" prop="status"> 
                <el-switch v-model="dhcpSettingFormData.status" active-value="on" inactive-value="off" />
              </el-form-item>
              <el-form-item :label="t('networkConfig.DNS1_label')" prop="DNS1"> 
                <el-input v-model="dhcpSettingFormData.DNS1" :placeholder="t('networkConfig.DNS1_label')" />
              </el-form-item>
              <el-form-item :label="t('networkConfig.DNS2_label')" prop="DNS2"> 
                <el-input v-model="dhcpSettingFormData.DNS2" :placeholder="t('networkConfig.DNS2_label')" />
              </el-form-item>
              <el-form-item :label="t('networkConfig.start_ip_label')" prop="start_ip"> 
                <el-input v-model="dhcpSettingFormData.start_ip" :placeholder="t('networkConfig.start_ip_label')" />
              </el-form-item>
              <el-form-item :label="t('networkConfig.end_ip_label')" prop="end_ip"> 
                <el-input v-model="dhcpSettingFormData.end_ip" :placeholder="t('networkConfig.end_ip_label')" />
              </el-form-item>
            </el-form>
          </div>
          <div class="dialog_bottom">
            <div class="confirm_btn" @click="handleSave">{{t('networkConfig.save_label')}}</div>
            <div class="cancel_btn" @click="dialogConfig.dialogVisible = false">{{t('networkConfig.cancel_label')}}</div>
          </div>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { 
  Connection,
  SetUp,
  Share,
  Monitor,
  Setting,
  Cpu,
  Operation
} from '@element-plus/icons-vue'

export default defineComponent({
  name: 'basicConfig',
})
</script>
<script setup  lang="ts">
import { useI18n } from 'vue-i18n'
import { BasicConfigApi } from '@/api/basicConfig'
import { ElNotification } from 'element-plus'
import {cloneDeep} from 'lodash'
import { ElNotificationFn } from '@/utils/computedUtils'
const { t } = useI18n()
const lanFormData = ref<any>({
  localIp:'',
  loading:false
})
const lanForm = ref<any>()
const localIpInput = ref<any>()
const lanFormRules =computed(() => {
  return {
    localIp:[{required:true,message:t('networkConfig.ip_address_label'),trigger:'blur'}]
  }
})
const saveLocalIp =async () => {
  lanFormData.value.loading = true
  await lanForm.value?.validate()
  await BasicConfigApi.setLocalIp({ip:lanFormData.value.localIp})
  ElNotification.success({
    title: t('set_success_label'),
    message: `本机IP${lanFormData.value.localIp}设置成功`,
  })
  lanFormData.value.loading = false
}
const getLocalIp =async () => {
  const {data} = await BasicConfigApi.getLocalIp()
  lanFormData.value.localIp = data.ip
}
const caaOrGreDataList = ref<any>([])
const currentCaaOrGreData = ref<any>({})
const getCaaOrGre =async () => {
  const {data} = await BasicConfigApi.getCaaOrGre()
  caaOrGreDataList.value = [data]
}
const caaOrGreFormData = ref<any>({})
const caaOrGreFormRef = ref<any>()
const caaOrGreFormRules = computed(() => {
  return {
    caa_ip:[{required:true,message:t('networkConfig.ip_address_label'),trigger:'change'}],
    caa_status:[{required:true,message:t('networkConfig.caaStart_label'),trigger:'change'}],
    gre_status:[{required:true,message:t('networkConfig.greStart_label'),trigger:'change'}]
  }
})

const editCaaOrGre = (row:any) => { 
  dialogConfig.value.dialogType = 'caaOrGre'
  caaOrGreFormData.value = cloneDeep(row)
  dialogConfig.value.title = t('networkConfig.set_caa_or_gre_label')
  dialogConfig.value.dialogVisible = true
  currentCaaOrGreData.value = row
}
const dialogConfig = ref<any>({
  title:'',
  width:'620',
  dialogVisible:false,
  dialogType:''
})
const handleSave =() => {
  switch(dialogConfig.value.dialogType){
    case 'caaOrGre':
      saveArrOrGre()
      break
    case 'reverseNat':
      saveReverseNat()
      break
    case 'wifiSetting':
      saveWifiSetting()
      break
    case 'dhcpSetting':
      saveDhcpSetting()
      break
  }
}
const saveArrOrGre = async () => {
  await caaOrGreFormRef.value?.validate()
  await BasicConfigApi.setCaaOrGre(caaOrGreFormData.value)
  ElNotification.success({
    title: t('set_success_label'),
    message: `CAA与GRE设置成功`,
  })
      dialogConfig.value.dialogVisible = false
      getCaaOrGre()
}
const reverseNatList = ref<any>([])
const postReverseNat =async () => {
  const {data} = await BasicConfigApi.reqPostReverseNat()
  reverseNatList.value = [data]
}
const reverseNatFormData = ref<any>({})
const reverseNatFormRef = ref<any>()
const reverseNatFormRules = computed(() => {
  return {
    ip:[{required:true,message:t('networkConfig.reverse_nat_label'),trigger:'change'}],
    status:[{required:true,message:t('networkConfig.enable_status_label'),trigger:'change'}]
  }
})
const editReverseNat = (row:any) => {
  dialogConfig.value.dialogType = 'reverseNat'
  reverseNatFormData.value = cloneDeep(row)
  dialogConfig.value.title = t('networkConfig.set_reverse_nat_label')
  dialogConfig.value.dialogVisible = true
}
const saveReverseNat = async () => {
  await reverseNatFormRef.value?.validate()
  await BasicConfigApi.reqSetReverseNat(reverseNatFormData.value)
  ElNotification.success({
    title: t('set_success_label'),
    message: `反向NAT设置成功`,
  })
  dialogConfig.value.dialogVisible = false
  postReverseNat()
}
const wifiSettingList = ref<any>([])
const getWifiSetting =async () => {
  const {data} = await BasicConfigApi.reqGetWifiSetting()
  wifiSettingList.value = data.list
}
const wifiSettingFormData = ref<any>({})
const wifiSettingFormRef = ref<any>()
const bandTypeOptions = ref<any>([
  {
    label:'2.4G',
    value:'2.4G'
  },
  {
    label:'5G',
    value:'5G'
  }
])
const wifiSettingFormRules = computed(() => {
  return {
    frequency_band:[{required:true,message:t('networkConfig.band_type_label'),trigger:'change'}],
    ssid:[{required:true,message:t('networkConfig.ssid_label'),trigger:'change'}],
    password:[{required:true,message:t('networkConfig.password_label'),trigger:'change'}],
    status:[{required:true,message:t('networkConfig.enable_status_label'),trigger:'change'}]
  }
})
const editWifiSetting = (row:any) => {
  dialogConfig.value.dialogType = 'wifiSetting'
  wifiSettingFormData.value = cloneDeep(row)
  dialogConfig.value.title = t('networkConfig.wifi_setting_label')
  dialogConfig.value.dialogVisible = true
}
const saveWifiSetting = async () => {
  await wifiSettingFormRef.value?.validate()
  await BasicConfigApi.reqSetWifiSetting(wifiSettingFormData.value)
  ElNotification.success({
    title: t('set_success_label'),
    message: `WIFI设置成功`,
  })
  dialogConfig.value.dialogVisible = false
  getWifiSetting()
}
const dhcpSettingList = ref<any>([])
const getDhcpSetting =async () => {
  const {data} = await BasicConfigApi.reqGetDhcpSetting()
  dhcpSettingList.value = [data]
}
const dhcpSettingFormData = ref<any>({})
const dhcpSettingFormRef = ref<any>()
const dhcpSettingFormRules = computed(() => {
  return {
    start_ip:[{required:true,message:t('networkConfig.start_ip_label'),trigger:'change'}],
    end_ip:[{required:true,message:t('networkConfig.end_ip_label'),trigger:'change'}],
    DNS1:[{required:true,message:t('networkConfig.DNS1_label'),trigger:'change'}],
    DNS2:[{required:true,message:t('networkConfig.DNS2_label'),trigger:'change'}],
    status:[{required:true,message:t('networkConfig.enable_status_label'),trigger:'change'}]
  }
})
const editDhcpSetting = (row:any) => {
  dialogConfig.value.dialogType = 'dhcpSetting'
  dhcpSettingFormData.value = cloneDeep(row)
  dialogConfig.value.title = t('networkConfig.dhcp_setting_label')
  dialogConfig.value.dialogVisible = true
}
const saveDhcpSetting = async () => {
  await dhcpSettingFormRef.value?.validate()
  await BasicConfigApi.reqSetDhcpSetting(dhcpSettingFormData.value)
  ElNotificationFn('success',t('set_success_label'))
  dialogConfig.value.dialogVisible = false
  getDhcpSetting()
}
const switchStates = ref({
  ipAcceleration: {
    status: '',
    loading: false
  },
  aloha: {
    status: '',
    loading: false
  }
})
const switchChangeFlag = ref<boolean>(false)
const handleSwitchChange = async (type: 'ipAcceleration' | 'aloha', value: string) => {
  if (!switchChangeFlag.value) return
  const state = switchStates.value[type]
  state.loading = true
  try {
    const api = type === 'ipAcceleration' 
      ? BasicConfigApi.reqSetIpAccelerationInfo 
      : BasicConfigApi.reqSetAloha  
    await api({ status: value })
    const namelabel = type === 'ipAcceleration' ? t('networkConfig.ip_acceleration_label') : t('networkConfig.aloha_label')
    const message = `${namelabel}: ${value === 'on' ? t('networkConfig.enable_label') : t('networkConfig.disable_label')
    }${t('networkConfig.set_success_label')}`

    ElNotificationFn('success', t('set_success_label'), message)
  } catch (err) {
    console.error(`Error setting ${type}:`, err)
  } finally {
    state.loading = false
  }
}
const initializeSwitchStates = async () => {
  try {
    const [ipAccelData, alohaData] = await Promise.all([
      BasicConfigApi.reqGetIpAccelerationInfo(),
      BasicConfigApi.reqGetAloha()
    ])    
    switchStates.value.ipAcceleration.status = ipAccelData.data.status
    switchStates.value.aloha.status = alohaData.data.status
    switchChangeFlag.value = true
  } catch (err) {
    console.error('Error initializing switch states:', err)
  }
}
onMounted(async () => {
  try{
    await Promise.all([
      getLocalIp(),
      getCaaOrGre(),
      postReverseNat(),
      getWifiSetting(),
      getDhcpSetting(),
      initializeSwitchStates()
    ])
  }catch(err){
    console.log(err)
  }
})
</script>

<style lang="scss" scoped>
@import '@/styles/form.scss';
@import '@/styles/table.scss';
@import '@/styles/input.scss';
@import '@/styles/card.scss';
@import "@/styles/switch.scss";
.basicConfig_container {
  padding: 20px;
}
.el-table {
  .el-button.is-text:not(.is-disabled):hover {
    background-color: transparent !important;
  }
}
:deep(.el-button.is-text) {
  color: #00D4FF;
}


.dialog_bottom{
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.m-t-20 {
  margin-top: 20px;
}

.m-l-10px {
  margin-left: 10px;
}

.m-r-10px {
  margin-right: 10px;
}

:deep(.el-icon) {
  font-size: 18px;
}
</style>
